package com.nbsaas.nbmall.shop.rest.resource;

import com.haoxuer.bigworld.pay.api.domain.page.TradeStreamPage;
import com.haoxuer.bigworld.pay.rest.conver.TradeStreamSimpleConver;
import com.haoxuer.discover.trade.data.dao.TradeAccountDao;
import com.haoxuer.discover.trade.data.dao.TradeStreamDao;
import com.haoxuer.discover.trade.data.entity.TradeAccount;
import com.haoxuer.discover.trade.data.entity.TradeStream;
import com.nbsaas.nbmall.shop.api.apis.ShopApi;
import com.nbsaas.nbmall.shop.api.domain.list.ShopList;
import com.nbsaas.nbmall.shop.api.domain.page.ShopPage;
import com.nbsaas.nbmall.shop.api.domain.request.*;
import com.nbsaas.nbmall.shop.api.domain.response.ShopResponse;
import com.nbsaas.nbmall.shop.data.dao.ShopDao;
import com.nbsaas.nbmall.shop.data.dao.ShopNotifierDao;
import com.nbsaas.nbmall.shop.data.entity.Shop;
import com.nbsaas.nbmall.shop.data.entity.ShopNotifier;
import com.nbsaas.nbmall.shop.rest.convert.ShopResponseConvert;
import com.nbsaas.nbmall.shop.rest.convert.ShopSimpleConvert;
import com.haoxuer.bigworld.tenant.data.entity.Tenant;
import com.haoxuer.discover.config.utils.ConverResourceUtils;
import com.haoxuer.discover.data.page.Filter;
import com.haoxuer.discover.data.page.Order;
import com.haoxuer.discover.data.page.Page;
import com.haoxuer.discover.data.page.Pageable;
import com.haoxuer.discover.data.utils.FilterUtils;
import com.nbsaas.nbmall.third.service.WxService;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.haoxuer.bigworld.member.rest.conver.PageableConver;
import com.haoxuer.bigworld.tenant.util.TenantBeanUtils;
import com.haoxuer.bigworld.member.data.dao.TenantUserDao;
import com.haoxuer.bigworld.member.data.dao.TenantUserDao;
import com.haoxuer.discover.area.data.dao.AreaDao;
import com.nbsaas.nbmall.common.data.dao.ChannelDao;
import com.haoxuer.discover.area.data.dao.AreaDao;
import com.haoxuer.discover.area.data.dao.AreaDao;
import com.nbsaas.nbmall.shop.data.dao.ShopCatalogDao;
import com.nbsaas.nbmall.shop.data.dao.ShopExtDao;

import java.util.ArrayList;
import java.util.List;

@Transactional
@Component
public class ShopResource implements ShopApi {

    @Autowired
    private ShopDao dataDao;

    @Autowired
    private TenantUserDao creatorDao;
    @Autowired
    private TenantUserDao bossDao;
    @Autowired
    private AreaDao provinceDao;
    @Autowired
    private ChannelDao channelDao;
    @Autowired
    private AreaDao areaDao;
    @Autowired
    private AreaDao cityDao;
    @Autowired
    private ShopCatalogDao shopCatalogDao;
    @Autowired
    private ShopExtDao extDao;


    @Autowired
    private ShopNotifierDao notifierDao;

    @Autowired
    private WxService wxService;

    @Autowired
    private TradeAccountDao tradeAccountDao;

    @Autowired
    private TradeStreamDao streamDao;


    @Override
    public ShopResponse create(ShopDataRequest request) {
        ShopResponse result = new ShopResponse();

        Shop bean = new Shop();
        bean.setTenant(Tenant.fromId(request.getTenant()));
        handleData(request, bean);
        dataDao.save(bean);
        result = new ShopResponseConvert().conver(bean);
        return result;
    }

    @Override
    public ShopResponse update(ShopDataRequest request) {
        ShopResponse result = new ShopResponse();
        if (request.getId() == null) {
            result.setCode(501);
            result.setMsg("无效id");
            return result;
        }
        Shop bean = dataDao.findById(request.getId());
        if (bean == null) {
            result.setCode(502);
            result.setMsg("无效id");
            return result;
        }
        handleData(request, bean);
        result = new ShopResponseConvert().conver(bean);
        return result;
    }

    private void handleData(ShopDataRequest request, Shop bean) {
       TenantBeanUtils.copyProperties(request,bean);
           if(request.getArea()!=null){
              bean.setArea(areaDao.findById(request.getArea()));
           }
           if(request.getCreator()!=null){
              bean.setCreator(creatorDao.findById(request.getCreator()));
           }
           if(request.getBoss()!=null){
              bean.setBoss(bossDao.findById(request.getBoss()));
           }
           if(request.getCity()!=null){
              bean.setCity(cityDao.findById(request.getCity()));
           }
           if(request.getChannel()!=null){
              bean.setChannel(channelDao.findById(request.getChannel()));
           }
           if(request.getExt()!=null){
              bean.setExt(extDao.findById(request.getExt()));
           }
           if(request.getProvince()!=null){
              bean.setProvince(provinceDao.findById(request.getProvince()));
           }
           if(request.getShopCatalog()!=null){
              bean.setShopCatalog(shopCatalogDao.findById(request.getShopCatalog()));
           }

    }

    @Override
    public ShopResponse delete(ShopDataRequest request) {
        ShopResponse result = new ShopResponse();
        if (request.getId() == null) {
            result.setCode(501);
            result.setMsg("无效id");
            return result;
        }
        dataDao.deleteById(request.getTenant(),request.getId());
        return result;
    }

    @Override
    public ShopResponse view(ShopDataRequest request) {
        ShopResponse result=new ShopResponse();
        Shop bean = dataDao.findById(request.getTenant(), request.getId());
        if (bean==null){
            result.setCode(1000);
            result.setMsg("无效id");
            return result;
        }
        result=new ShopResponseConvert().conver(bean);
        return result;
    }
    @Override
    public ShopList list(ShopSearchRequest request) {
        ShopList result = new ShopList();

        List<Filter> filters = new ArrayList<>();
        filters.add(Filter.eq("tenant.id", request.getTenant()));
        filters.addAll(FilterUtils.getFilters(request));
        List<Order> orders = new ArrayList<>();
        if ("asc".equals(request.getSortMethod())){
           orders.add(Order.asc(""+request.getSortField()));
        }
        else if ("desc".equals(request.getSortMethod())){
           orders.add(Order.desc(""+request.getSortField()));
        }else{
           orders.add(Order.desc("id"));
        }
        List<Shop> organizations = dataDao.list(0, request.getSize(), filters, orders);

        ShopSimpleConvert convert=new ShopSimpleConvert();
        ConverResourceUtils.converList(result, organizations,convert);
        return result;
    }

    @Override
    public ShopPage search(ShopSearchRequest request) {
        ShopPage result=new ShopPage();
        Pageable pageable = new PageableConver().conver(request);
        pageable.getFilters().addAll(FilterUtils.getFilters(request));
        pageable.getFilters().add(Filter.eq("tenant.id", request.getTenant()));
        if ("asc".equals(request.getSortMethod())){
            pageable.getOrders().add(Order.asc(""+request.getSortField()));
        }
        else if ("desc".equals(request.getSortMethod())){
            pageable.getOrders().add(Order.desc(""+request.getSortField()));
        }else{
            pageable.getOrders().add(Order.desc("id"));
        }
        Page<Shop> page=dataDao.page(pageable);

        ShopSimpleConvert convert=new ShopSimpleConvert();
        ConverResourceUtils.converPage(result,page,convert);
        return result;
    }

    @Override
    public ShopResponse audit(ShopDataRequest request) {
        ShopResponse result = new ShopResponse();
        if (request.getId() == null) {
            result.setCode(501);
            result.setMsg("无效id");
            return result;
        }
        if (request.getAuditState() == null) {
            result.setCode(502);
            result.setMsg("无效审核状态");
        }
        Shop bean = dataDao.findById(request.getId());
        if (bean == null) {
            result.setCode(502);
            result.setMsg("无效id");
            return result;
        }
        bean.setAuditState(request.getAuditState());
        return result;
    }

    @Override
    public TradeStreamPage stream(ShopSearchRequest request) {
        TradeStreamPage result = new TradeStreamPage();
        if (request.getUser() == null) {
            result.setCode(501);
            result.setMsg("无效token");
            return result;
        }
        Shop shop = dataDao.findById(request.getTenant(),request.getShop());
        if (shop == null) {
            result.setCode(1001);
            result.setMsg("无效token");
            return result;
        }
        TradeAccount account = shop.getTradeAccount();
        if (account == null) {
            account = tradeAccountDao.initNormal();
            shop.setTradeAccount(account);
        }
        result.setMoney(account.getAmount());
        Pageable pageable = new PageableConver().conver(request);
        pageable.getOrders().add(Order.desc("id"));
        pageable.getFilters().add(Filter.eq("account.id", account.getId()));

        Page<TradeStream> page = streamDao.page(pageable);
        ConverResourceUtils.converPage(result, page, new TradeStreamSimpleConver());
        return result;
    }

    @Override
    public ShopResponse bind(String code, String state) {

        ShopResponse result = new ShopResponse();
        try {
            Shop shop = dataDao.findById(Long.valueOf(state));
            if (shop != null) {
                WxOAuth2AccessToken token = wxService.getWxMpService(shop.getTenant().getId()).getOAuth2Service().getAccessToken(code);
                if (token != null && token.getOpenId() != null) {
                    ShopNotifier temp = notifierDao.one(Filter.eq("shop.id", shop.getId()),
                            Filter.eq("openId", token.getOpenId()));
                    if (temp != null) {
                        result.setCode(502);
                        result.setMsg("该用户已经添加过了");
                        return result;
                    }
                    ShopNotifier bean = new ShopNotifier();
                    bean.setShop(shop);
                    bean.setTenant(shop.getTenant());
                    bean.setOpenId(token.getOpenId());
                    notifierDao.save(bean);
                }
            }
        } catch (WxErrorException e) {

            e.printStackTrace();
        }
        return result;
    }
}
